<?php

function loadModule($module, $params = array())
{
    global $_user, $_session;

    if ($params) {
        extract($params);
    }

    $content = '';
    if (file_exists($module_file = MODULE_PATH . $module . '.php')) {
        ob_start();
        include $module_file;
        $content = ob_get_contents();
        ob_end_clean();
    }
    return $content;
}

function module($module, $params = array(), $cache_name = '', $expire = -1)
{
    if (!$cache_name)
        $cache_name = $module;

    $content = '';
    if ($expire < 0) {
        // no cache need
        $content = loadModule($module, $params);
    } else {
        // need cache for expire time
        if (!($content = cache('cache:' . $cache_name))) {
            // no cache or cache expire out
            $content = loadModule($module, $params);

            cache('cache:' . $cache_name, $content, $expire);
        }
    }
    return $content;
}

function show($view)
{
    if (file_exists(VIEW_PATH . $view))
        include VIEW_PATH . $view;
    else if (file_exists(VIEW_PATH . $view . '.php'))
        include VIEW_PATH . $view . '.php';
    else if (file_exists(VIEW_PATH . $view . '.htm'))
        include VIEW_PATH . $view . '.htm';
    else if (file_exists(VIEW_PATH . $view . '.html'))
        include VIEW_PATH . $view . '.html';
    else
        return false;
}

function showHumanTime($timestamp)
{
    $time_offset = time() - $timestamp;

    if ($time_offset < 3600) {
        // 1小时内的
        return ($time_offset <= 0 ? '1' : ceil($time_offset / 60)) . '分钟前';
    } /*
    else if ($time_offset < 3600 * 6)
    {
        // 6小时内的
        $hour = floor($time_offset / 3600);
        $mini = ceil(($time_offset - $hour * 3600) / 60);
        return $hour . '小时' . $mini . '分钟前';
    }*/

    else {
        $today_time = strtotime(date('Y-m-d'));
        $yesterday_time = strtotime(date('Y-m-d', time() - 3600 * 24));
        if ($timestamp > $today_time) {
            // 今天
            return '今天 ' . date('H:i', $timestamp);
        } else if ($timestamp > $yesterday_time) {
            // 昨天
            return '昨天 ' . date('H:i', $timestamp);
        } else {
            return date('Y-m-d H:i', $timestamp);
        }
    }
}

function return_ip()
{
    $ip = "-1";
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_a = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        for ($i = 0; $i < count($ip_a); $i++) { //
            $tmp = trim($ip_a[$i]);
            if ($tmp == 'unknown' || $tmp == '127.0.0.1' || strncmp($tmp, '10.', 3) == 0 || strncmp($tmp, '172', 3) == 0 || strncmp($tmp, '192', 3) == 0)
                continue;
            $ip = $tmp;
            break;
        }
    } else if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
    } else if (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = trim($_SERVER['REMOTE_ADDR']);
    } else {
        $ip = "-1";
    }
    return $ip;
}

// 36进制与10进制互转
define('CONVERT_10_36_ALPHAS', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function convert_36to10($num_36)
{
    $num_36 = (string)$num_36;
    $rules = CONVERT_10_36_ALPHAS;
    $num = 0;

    while ($num_36) {
        $num += strpos($rules, $num_36{0}) * pow(36, strlen($num_36) - 1);

        if (strlen($num_36) == 1) {
            $num_36 = '';
        } else {
            $num_36 = substr($num_36, 1);
        }
    }

    return $num;
}

function convert_10to36($num_10)
{
    $rules = CONVERT_10_36_ALPHAS;
    $num_10 = (string)$num_10;
    $num = '';
    $result = $num_10;

    while ($result != 0) {
        $result = floor($num_10 / 36);
        $num = $rules{$num_10 - $result * 36} . $num;

        $num_10 = $result;
    }
    return $num;
}

function gbk2utf8($data)
{
    if (is_array($data)) {
        return array_map('gbk2utf8', $data);
    } else if (is_object($data)) {
        return array_map('gbk2utf8', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'UTF-8', 'GBK');
}

function utf8togbk($data)
{
    if (is_array($data)) {
        return array_map('utf8togbk', $data);
    } else if (is_object($data)) {
        return array_map('utf8togbk', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'GBK', 'UTF-8');
}

function curUrlName($str)
{
    $cur_url_array = explode('.', $str);
    $cur_url_name = str_replace("/", "", $cur_url_array[0]);
    return $cur_url_name;
}

//return big user_face
function big_user_face($str)
{
    return str_replace('/50/', '/100/', $str);
}

//return small user_face
function small_user_face($str)
{
    return str_replace('/50/', '/10/', $str);
}

function isUrl($url)
{
    return preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i', $url);
}

function mb_replace($pattern, $replacement, $string, $sourceEncoding = 'gbk')
{
    $string = mb_convert_encoding($string, "utf-8", $sourceEncoding);
    $pattern = mb_convert_encoding($pattern, "utf-8", $sourceEncoding);
    $replacement = mb_convert_encoding($replacement, "utf-8", $sourceEncoding);
    $string = mb_ereg_replace($pattern, $replacement, $string);
    $ret = mb_convert_encoding($string, $sourceEncoding, "utf-8");
    return $ret;
}

//截取中文字符,支持一个英文算两个字符，如果两个英文算一个字的截取传入280即可代表140
function cnSubStr($string, $sublen, $tip = '')
{
    $len = strlen($string);
    if ($sublen >= $len) {
        return $string;
    }
    $s = "";
    for ($i = 0; $i < $sublen; $i++) {
        if (ord($string{$i}) > 127) {
            $s .= $string{$i} . $string{++$i};
            continue;
        } else {
            $s .= $string{$i};
            continue;
        }
    }

    if (strlen($s) >= $len)
        return $s;
    return $s . $tip;
}

//去除空格
function trim_space($s)
{
    $s = mb_ereg_replace('^(　| )+', '', $s);
    $s = mb_ereg_replace('(　| )+$', '', $s);
    return $s;
}

//网页内容抓取
function curl_get_contents($url, $timeout = 3)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 缓存一天
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

//curl Post数据
function curl_post_contents($url, $data = array(), $cookiepath = '')
{
    $userAgent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
    $referer = $url;
    if (!is_array($data) || !$url) return '';
    $post = '';
    foreach ($data as $key => $value) {
        $post .= $key . '=' . urlencode($value) . '&';
    }
    rtrim($post, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置超时
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); //用户访问代理 User-Agent
    curl_setopt($ch, CURLOPT_REFERER, $referer); //设置 referer
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); //跟踪301
    curl_setopt($ch, CURLOPT_POST, 1); //指定post数据
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //添加变量
    //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiepath); //COOKIE的存储路径,返回时保存COOKIE的路径
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

//@caixudong gbk的explode，多字节处理，防止5c问题发生
function gbk_explode($l, $s)
{
    $s = mb_convert_encoding($s, "utf-8", "GBK");
    $a = explode($l, $s);
    foreach ($a as &$v) {
        $v = mb_convert_encoding($v, "GBK", "utf-8");
    }
    return $a;
}


//按照KEY取出数组重复
function array_union_key($a, $b)
{
    return array_merge(array_diff_key($a, $b), $b);
}

// array_diff's bug for PHP5.2.6-5.3.3
function my_array_diff($a1, $a2)
{
    $a2 = array_flip((array)$a2);
    foreach ((array)$a1 as $key => $item) {
        if (isset($a2[$item])) {
            unset($a1[$key]);
        }
    }
    return $a1;
}

function time_debug($name = null)
{
    static $start_time;
    if (!$start_time)
        $start_time = microtime(true);
    static $debug_points;
    if (!$debug_points)
        $debug_points = array();
    if (!$name)
        return $debug_points;
    $last_time = $debug_points[count($debug_points) - 1]['offset_time'];
    $debug_points[] = array(
        'name' => $name,
        'offset_time' => microtime(true) - $start_time,
        'exec_time' => microtime(true) - $start_time - $last_time,
    );

    return $debug_points;
}

//取得URL的主域名
function is_whoopsfeed_domain($url)
{
    $tmp = parse_url($url);
    $tmp_host = array_reverse(explode('.', $tmp['host']));
    $host_domain = $tmp_host[1] . '.' . $tmp_host[0];
    if ($host_domain == 'whoopsfeed.com')
        return true;
    else
        return false;
}

/**
 * 设置cookie函数
 * @param  string $name   cookie键
 * @param  string $value  cookie值
 * @param  int    $expire 过期时间
 * @return void
 */
function wfCookie($name, $value, $expire)
{
    setcookie($name, $value, time() + $expire, '/', '.pps.tv');
}

/**
 * 获得当前工作的目录+文件名 给老包统计数据分析使用
 * @param  str $cur_path  调用文件的全路径
 * @return $str 返回字符串
 * author @snow 2011-1-11
 */
function getCurDirFile($cur_path)
{
    $root_name = $_SERVER['DOCUMENT_ROOT'];
    $cur_dir_file = str_replace($root_name, '', $cur_path);
    return $cur_dir_file;
}

//去除空格判断空
function trim_empty($str, $is_zh = false)
{
    $str = $is_zh ? trim_space($str) : trim($str);
    return empty($str);
}

//获取HOST
function getHttpHost()
{

    return "http://" . (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
}


/**
 * 跳转页面--重定向
 * @param  string $url
 * @param int $status
 * @return void
 */
function redirect($url, $status = 302)
{
    header('Status: ' . $status);
    header('Location: ' . $url);
    exit();
}

/**
 * 判读是否是 Ajax 请求
 * @return boolean
 */
function isAjax()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
}

/**
 * 根据性别获取他或者她
 *
 * @param int $sex
 * @return string
 */
function sheorhe($sex = 2)
{
    return ($sex == 2 || empty($sex)) ? '他' : '她';
}

/**
 * 格式化时间
 * @param  $time 时间妙
 * @return string
 * wenhui
 */
function formatTime($time)
{
    $time = $time / 1000;
    $minutes = floor($time / 60);
    $second = floor($time % 60);
    if ($minutes < 10) {
        $minutes = '0' . $minutes;
    }
    if ($second < 10) {
        $second = '0' . $second;
    }
    return $minutes . ':' . $second;
}

/**
 * 过虑HTML
 * @param  string $var
 * @return string
 */
function htmlFilter($var)
{
    $search = array(
        "'<script[^>]*?>.*?<\/script>'si",
        "'<html[^>]*?>.*?<body[^>]*?>'si",
        "'<\/body>.*?<\/html>'si",
        "'<style[^>]*?>.*?<\/style>'si",
        "'<link[^>]*?\s*[\/]?>'si",
        "'<iframe[^>]*?>.*?<\/iframe>'si",
        "'<form[^>]*?>(.*?)<\/form>'si",
        "'<textarea[^>]*?>.*?<\/textarea>'si",
        //"'\s*id\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'\s* clas\s*s\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'<!--.*?-->'si",
    );
    $replace = array('', '', '', '', '', '', '', '', '', '', '');
    $var = preg_replace($search, $replace, $var);
    $trans = array(
        '?' => '&#63;',
        '\\' => '&#92;',
        '`' => '',
    );
    return strtr($var, $trans);
}

function repTag($tag_str)
{
    $trans = array(
        "," => ";",
        " " => ";",
        "，" => ";"
    );
    return strtr($tag_str, $trans);
}

/**
 * 文本换行
 */
function lineFeed($content)
{
    $trans = array(
        "\r\n" => '<br />',
        "\n" => '<br />',
        "\r" => '<br />'
    );
    return strtr($content, $trans);
}

/**
 * 判断远程图片是否存在
 * @param string $url 图片地址
 * @return true or false
 * author wuzhongbo
 * data 2011-7-18
 */
function checkRemoteImgExists($url)
{
    $curl = curl_init($url);
    // 不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    // 发送请求
    $result = curl_exec($curl);
    $found = false;
    // 如果请求没有发送失败
    if ($result !== false) {
        // 再检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode == 200) {
            $found = true;
        }
    }
    curl_close($curl);

    return $found;
}


/**
 * 距离现在时间
 * @param $timestamp 时间戳
 */
function showUGCTime($timestamp)
{
    $time_offset = time() - $timestamp;

    if ($time_offset < 60) {
        // 1分钟内
        return '刚刚';
    } else if ($time_offset < 3600) {
        // 1小时内
        return ceil($time_offset / 60) . '分钟前';
    } else if ($time_offset < 3600 * 24) {
        // 24小时内
        $hour = floor($time_offset / 3600);
        return $hour . '小时前';
    } else if ($time_offset < 3600 * 24 * 30) {
        // 30天内
        $day = floor($time_offset / 86400);
        return $day . '天前';
    } elseif ($time_offset > 3600 * 24 * 30) {
        //超过30天
        $month_stamp = 86400 * 30;
        $month = floor($time_offset / $month_stamp);
        return $month . '个月前';
    }
}


/*
 * 对二维数组,按第二维数组中的某个键值对进行排序
 * @param array $arr 二维数组如 array('0'=> array('v_title' => '视频2','v_image'=>'地址2','v_sort'=>'2'),'1'=>array('v_title' => '视频1','v_image'=>'地址1','v_sort'=>'1'))
 * @param string 二维数组中的某个键值对 如（v_sort）
 * @param int $sort_flags 排序方式 0:升序，1:降序
 * @return array 排序后的数二维数组
 * @date 2011-09-22
 * @ + 增加一个排序方式
 */
function array_sort($arr, $field, $sort_flags = 0)
{
    $sort_tmp = array();
    $arr_tmp = array();
    foreach ($arr as $key => $value) {
        $sort_tmp[$key] = $value[$field]; //取出排列顺序字段
    }
    asort($sort_tmp); //按值排序，保留键的对应,可校正排序相同的情况
    foreach ($sort_tmp as $k => $v) {
        $arr_tmp[] = $arr[$k];
    }
    return $sort_flags ? array_reverse($arr_tmp) : $arr_tmp;
}

/**
 * 处理接口返回格式
 * @param $data
 * @param $format
 * @param string $jsonp
 * @return string
 */
function formatData($data, $format, $jsonp = "")
{
    $data = gbk2utf8($data);
    if ($format == "json") {
        return json_encode(($data));
    }
    if ($format == "xml") {
        $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> ";
        $xml .= "<response>";
        $xml .= formatXml($data);
        $xml .= "</response>";
        return $xml;
    }
    if ($format == "jsonp") {
        return $jsonp . "('" . json_encode($data) . "')";
    }
}

/**
 * 处理xml的方法
 * @param $data
 * @return string
 */
function formatXml($data)
{
    $xml = '';
    foreach ($data as $key => $val) {
        $xml .= "<{$key}>";
        if (is_array($val)) {
            $xml .= formatXml($val);
        } else {
            $xml .= "{$val}";
        }
        $xml .= "</{$key}>";
    }
    return $xml;
}

function toXml($data, $xml_setting = array(), & $xml = null, & $parent_node = null)
{
    $xml_setting_default = array('root' => 'xml', 'charset' => 'utf-8', 'num_key' => 'item', 'version' => '1.0');
    $xml_setting = is_array($xml_setting) ? $xml_setting : array();
    $xml_setting = array_merge($xml_setting_default, $xml_setting);
    if ($xml == null) {
        $xml = new DOMDocument($xml_setting['version'], $xml_setting['charset']);
        $xml->formatOutput = false;
        $parent_node = $xml->createElement($xml_setting['root']);
        $xml->appendChild($parent_node);
    }
    if ($xml == null || $parent_node == null) {
        return false;
    }
    foreach ($data as $key => $value) {
        $node_name = is_numeric($key) ? $xml_setting['num_key'] : $key;
        $node = $xml->createElement($node_name);
        $parent_node->appendChild($node);
        if (!is_array($value)) {
            $child_node = $xml->createTextNode($value);
            $node->appendChild($child_node);
        } else {
            $child_node = toXml($value, $xml_setting, $xml, $node);
        }

    }
    return $xml->saveXML();
}

/*
 * 根据宝宝地址获取商品标识(暂只支持 淘宝 天猫)
 * taobao tmall 获取 id
 实例
 * $ar = array(
 'http://item.taobao.com/item.htm?id=9523770399&ali_refid=a3_619362_1007:1102373933:7:46702465U84y78608587678s868v3I:7bcdc59fb0c21ce96e901436b439fd77&ali_trackid=1_7bcdc59fb0c21ce96e901436b439fd77',
 'http：//item.taobao.com/auction/item_detail.htm?item_num_id=9523770399&ali_refid=a3_619362_1007:1102373933:7:46702465U84y78608587678s868v3I:7bcdc59fb0c21ce96e901436b439fd77&ali_trackid=1_7bcdc59fb0c21ce96e901436b439fd77',
 'http://item.taobao.com/item.htm?id=9523770399',
 'http：//item.taobao.com/auction/item_detail.htm?item_num_id=9523770399'
 );

 foreach($ar as $v) {
   $u = parse_url($v);
   parse_str($u['query'], $var);
   print_r($var);
 }

 $str="http://item.taobao.com/item.htm?id=9523770399";
 $mode="/\?item_num_id=(\d*)|&item_num_id=(\d*)|\?id=(\d*)|&id=(\d*)/";
 preg_match($mode,$str,$arr);

 $arr=array_diff($arr, array(null));
 echo $arr=implode(array_diff($arr, array($arr[0])));
 exit;
 */
function getDomainAndIdByBaobeiUrl($url){

    $url_from = array('tmall', 'taobao');

    $return_arr = array();

    //获取url中id
    $mode="/\?id=(\d*)|&id=(\d*)/";
    preg_match($mode,$url,$arr);

    $arr = array_diff($arr, array(null));
    $id  = implode(array_diff($arr, array($arr[0])));

    //获取url中domain
    $url_arr = parse_url($url);
    $url_host = array_reverse(explode('.', $url_arr['host']));
    $host_domain = $url_host[1];

    if (in_array($host_domain, $url_from) && $id && is_numeric($id)) {
        $return_arr['id'] = $id;
        $return_arr['domain'] = $host_domain;

        switch($host_domain){
            case 'taobao':
                $return_arr['url'] = 'http://item.taobao.com/item.htm?id='.$id;
                break;
            case 'tmall':
                $return_arr['url'] = 'http://detail.tmall.com/item.htm?id='.$id;
                break;
        }
    }

    return $return_arr;
}

?>